package com.aisile.crowd_funding.system.shiro;

import com.aisile.crowd_funding.common.config.Constant;
import com.aisile.crowd_funding.common.utils.MD5Utils;
import com.aisile.crowd_funding.system.pojo.SysUser;
import com.aisile.crowd_funding.system.service.UserService;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @标题 MyRealm
 * @作者 Mr.chen
 * @创建日期 2018/12/5 16:19
 * @版本号 1.0
 **/
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    /**
     * 授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //根据用户名  去数据库  查用户
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        String userName=token.getUsername();
        //对传过来的密码进行加密
        String password= new String(token.getPassword());
        SysUser user=userService.findByUserName(userName);
        if(user==null){
            //没有查询到用户就抛出异常
            throw new UnknownAccountException();

        }
        if(!user.getPassword().equals(password)){
           //密码不正确
            throw new AccountException();

        }

        if(Constant.UserStuatus==user.getStatus()){
           //禁用状态
            throw new LockedAccountException();
        }
        //登录成功将用户交给shiro 处理 getName()是当前域的名称
        SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(user,user.getPassword(),getName());


        return simpleAuthenticationInfo;
    }
}
